//
//  HJStatusViewModel.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/24.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import SDWebImage

class HJStatusViewModel: NSObject {
    static let sharedInstance: HJStatusViewModel = HJStatusViewModel()
    private var loading: Bool = false
    // load status data
    func loadStatus(since_id: Int64, max_id: Int64, finished: (statuses: [HJStatuses]?, error: NSError?) -> ()) {
        if loading {
            HJPrint(msg: "有人正在加载微博数据")
            // 自定义错误
            finished(statuses: nil, error: HJNetworkToolError.RepeatRefresh.error())
            return
        }
        // 之前没有人在加载数据
        loading  = true
        
        let urlString = "2/statuses/home_timeline.json"
        var parameters = [String : AnyObject]()
        if since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong: max_id - 1)
        }
        HJNetworkTool.sharedInstance.requestGET(urlString, parameters: parameters) { (result, error) -> () in
            // 微博数据加载完成，改为false ，以便再次调用
            self.loading = false
            if error != nil {
                finished(statuses: nil, error: error)
                return
            }
            // 获取返回数据中的微博数据
            let statusesArray = result?["statuses"] as? [[String: AnyObject]]
            // 定义空数组保存模型数据
            var statuses = [HJStatuses]()
            for dict in statusesArray! {
                let status = HJStatuses(dict: dict)
                statuses.append(status)
            }
            
            self.cacheWebImage(statuses, finished: finished)
            
        }
    }
    
    // 缓存微博图片
    private func cacheWebImage(statuses: [HJStatuses], finished: (statuses: [HJStatuses]?, error: NSError?) -> ()) {
        let group = dispatch_group_create()
        var length: CGFloat = 0
        for status in statuses {
            var downloadURLs = status.storePictureURLs
            if downloadURLs == nil {
                downloadURLs = status.retweeted_status?.storePictureURLs
            }
            if downloadURLs == nil {
                continue
            }
            if downloadURLs?.count == 1 {
                let url = downloadURLs![0]
                // 在异步任务之前进入组
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    // 不管是下载成功还是失败,任务都完成了.就需要离开组
                    dispatch_group_leave(group)
                    if error != nil {
                        HJPrint(msg: "SDWebImageManager下载图片失败: \(url)")
                        return
                    }
//                    HJPrint(msg: "SDWebImageManager下载图片成功: \(url)")
                    let data = UIImagePNGRepresentation(image)!
                    length += CGFloat(data.length)
                })
            }
        }
        // 所有模型的图片都下载完成才通知
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            let len = length / 1024 / 1024.0
            let l = String(format: "%.2f", arguments: [len])
            print("所有图片都缓存完成: \(l) MB")
            // 所有图片都缓存完成,通知控制器来显示微博数据
            finished(statuses: statuses, error: nil)
        }
    }
}
